#-*- coding:UTF-8 -*-
'''
Created on 2012-7-17
Sock Server
@author: Administrator
'''
from socket import *
from time import ctime

HOST = '127.0.0.1'
PORT = 21567
BUFSIZE = 1024

def testTcp():
    tcpSerSock = socket(AF_INET, SOCK_STREAM)
    #绑定主机和端口
    tcpSerSock.bind((HOST, PORT))
    #设置最大监听数为5,超过的被拒绝掉
    tcpSerSock.listen(1)
    
    try:
        while True:
            print 'waiting for connection...'
            tcpCliSock, addr = tcpSerSock.accept()
            print '.... connection from :', addr
    
            while True:
                data = tcpCliSock.recv(BUFSIZE)
                if not data:
                    break
                tcpCliSock.send('[%s] %s' % (ctime(), data))
            tcpCliSock.close()
    except EOFError, e:
        print e,
    except KeyboardInterrupt, k:
        print k,
    finally:    
        tcpSerSock.close();

def testUdp():
    udpSerSock = socket(AF_INET, SOCK_DGRAM)
    udpSerSock.bind((HOST, PORT))
    
    while True:
        print 'waiting for message.....'
        data, addr = udpSerSock.recvfrom(BUFSIZE)
        udpSerSock.sendto('[%s] %s' % (ctime(), data), addr)
        print '...received from and returned to:', addr
    udpSerSock.close()
